import pickle
import os
import os.path

class Object(object):
  """Wrapper around object to allow adding properties on the fly."""
  pass

class Build(object):
  """Holds the persistent information for a build configuration."""
  
  def __init__(self):
    """Initializes the build environment with defaults."""
    self.output = None
    self.config = None
    self.state = Object()
    self.tools = None
    
  def load(self):
    """Loads the build environment from the cache in the output location."""
    self.tools = self._load_object('tools')
    self.config = self._load_object('config')
    self.state = self._load_object('state')
    
  def save(self):
    """Caches the build environment into the output location."""
    self._save_object('tools', self.tools)
    self._save_object('config', self.config)
    self._save_object('state', self.state)
  
  def save_state(self):
    self._save_object('state', self.state)
    
  def _load_object(self, filename):
    """Loads an object from a file in the output location."""
    path = os.path.join(self.output, filename)
    if os.path.exists(path):
      return pickle.load(open(path, 'r'))
    else:
      return None
      
  def _save_object(self, filename, obj):
    """Saves an object to a file in the output location."""
    path = os.path.join(self.output, filename)
    pickle.dump(obj, open(path, 'w'))

